/**
 * 审核结果提交
 */

import Taro from "@tarojs/taro";
import { useReactive } from "ahooks";

import useFetch from "./useFetch";
import ApiWorkflow from "@/api/workflow";
import { useState } from "react";
import { TaskStep } from "@/types/global";

export default (fnResult: (status: "success" | "fail") => void) => {
  // 拿到当前审批节点（如果当前用户可以审批）
  const [approverNode, setApproverNode] = useState<TaskStep>();

  const model = useReactive<{
    workItemId?: number;
    /**
     * 审核结果，1-通过，2-拒绝
     */
    auditResult?: 1 | 2;
    auditRemark?: string;
  }>({});

  // 审批操作
  const { loading, run } = useFetch(ApiWorkflow.approveAudit, "POST", {
    manual: true,
    showLoading: true,
    onSuccess() {
      setApproverNode(undefined);
      model.workItemId = undefined;
      Taro.showToast({ title: "操作成功" });
      fnResult?.("success");
    },
  });

  /**
   * @param auditResult 审核结果 1通过，2驳回
   * @param auditRemark 审核原因/备注
   */
  const submit = async (auditResult: 1 | 2 = 1, auditRemark?: string) => {
    const isPass = auditResult === 1;

    // @ts-expect-error
    const { confirm, content } = await Taro.showModal({
      title: isPass ? "审批通过" : "审批驳回",
      content: "",
      // @ts-expect-error
      editable: isPass,
      placeholderText: "输入审批备注(非必填)",
      confirmColor: isPass ? "#07c160" : "#E31812",
      confirmText: isPass ? "通过" : "驳回",
    });

    if (confirm) {
      // 审批结论
      model.auditResult = auditResult;
      // 审批备注
      model.auditRemark = isPass ? content : auditRemark;
      await run(model);
    }
  };

  // 审核通过
  const approved = () => submit(1);
  const rejected = (remark?: string) => submit(2, remark);

  const setApproveNode = (workerId: any, approve: TaskStep) => {
    model.workItemId = workerId;
    setApproverNode(approve);
  };

  return {
    model,
    loading,
    approverNode,

    submit,
    approved,
    rejected,
    setApproveNode,
  };
};
